<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <script th:src="@{/js/jquery-3.7.1.min.js}"></script>
</head>
<body>
<div class="container mt-3">
    <h1>用户列表</h1>
    <p>上下文类可用于为表格、表格行或表格单元格着色。可以使用的类有：.table-primary、.table-success、.table-info、.table-warning、.table-danger、.table-active、.table-secondary、.table-light 和 .table-dark：</p>
    <button class="btn btn-primary mb-3" onclick="showAddUserModal()">添加用户</button>
    <table class="table table-dark table-hover">
        <thead>
        <tr>
            <th>id</th>
            <th>姓名</th>
            <th>性别</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody th:each="item : ${users}">
        <tr th:id="'userRow'+${item.id}" >
            <td th:text="${item.id}">1</td>
            <td th:text="${item.name}">Default</td>
            <td th:text="${item.sex}">Male</td>
            <td>
                <button class="btn btn-warning" th:onclick="showEditUserModal([[${item.id}]])">编辑</button>
                <button class="btn btn-danger" th:onclick="deleteUser([[${item.id}]])">删除</button>
            </td>
        </tr>
        </tbody>
    </table>
</div>



<!-- Add/Edit User Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="userId">
                    <div class="mb-3">
                        <label for="name" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="sex" class="form-label">性别</label>
                        <input type="text" class="form-control" id="sex" required>
                    </div>
                    <button type="submit" class="btn btn-primary">保存</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {

        const token = localStorage.getItem('jwtToken');
        if (!token) {
            alert('No token found, please login first.');
            window.location.href = "/login"; // 跳转到登录页面
            return;
        }


        $("#userForm").submit(function(event) {
            event.preventDefault();
            saveUser();
        });
    });

    function showAddUserModal() {
        $("#modalTitle").text("添加用户");
        $("#userForm")[0].reset();
        $("#userId").val("");
        $("#userModal").modal('show');
    }


    function showEditUserModal(id) {
        $.ajax({
            url: `/myuser/find/${id}`,
            method: 'GET',
            success: function(response) {
                let user = response.data;
                $("#modalTitle").text("编辑用户");
                $("#userId").val(user.id);
                $("#name").val(user.name);
                $("#sex").val(user.sex);
                $("#userModal").modal('show');
            }
        });
    }

    function saveUser() {
        let id = $("#userId").val();
        let url = id ? `/myuser/update/${id}` : '/myuser/add';
        let method = id ? 'PUT' : 'POST';
        let user = {
            name: $("#name").val(),
            sex: $("#sex").val()
        };

        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify(user),
            success: function(response) {

                /*  result{code:200,msg:ok ,data:user{}}*/
                $("#userModal").modal('hide');
                if (id) {
                    updateTableRow(id, user);
                } else {
                    addTableRow(response.data);
                }
            }
        });
    }

    function deleteUser(id) {
        if (confirm("你确定要删除这个用户吗？")) {
            $.ajax({
                url: `/myuser/delete/${id}`,
                method: 'DELETE',
                success: function() {
                    removeTableRow(id);
                }
            });
        }
    }

    function addTableRow(user) {
        let row = `
            <tr id="userRow${user.id}">
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.sex}</td>
                <td>
                    <button class="btn btn-warning" onclick="showEditUserModal(${user.id})">编辑</button>
                    <button class="btn btn-danger" onclick="deleteUser(${user.id})">删除</button>
                </td>
            </tr>
        `;
        $("table tbody tr").append(row);
    }

    function updateTableRow(id, user) {

        let row = $(`#userRow${id}`);

        row.find("td:eq(1)").text(user.name);
        row.find("td:eq(2)").text(user.sex);
    }

    function removeTableRow(id) {
        $(`#userRow${id}`).remove();
    }
</script>

<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
</body>
</html>
